/**
 * Copyright (c) 2017-2018, zengjintao (1913188966@qq.com).
 * <p>
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.gnu.org/licenses/lgpl-3.0.txt
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.fast.framework.aop;
import java.io.Serializable;
import java.util.List;

import org.aopalliance.intercept.MethodInterceptor;

import com.fast.framework.aop.annotation.PointCut;
import com.fast.framework.ioc.annoation.Bean;
import com.fast.framework.util.PackageUtil;
import com.fast.framework.web.config.JFastConfig;
import com.google.inject.Binder;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.matcher.Matchers;

/**
 * guice管理器
 * @author zengjintao
 * @version 1.0
 * 2017年10月13日下午8:29:28
 */
public class GuiceManager implements com.google.inject.Module{

	private static final JFastConfig jfastConfig = JFastConfig.getJfastConfig();
	
	private static final InteceptorManager inteceptorManager = InteceptorManager.getInteceptorManager();
	
	private static final GuiceManager guiceManger = new GuiceManager();
	
	private  Injector injector ;

	
	private GuiceManager(){
		injector = Guice.createInjector(this);
	}
	
	public static GuiceManager getGuiceManger(){
		return guiceManger;
	}
	
	public  Injector getInjector() {
		return injector;
	}

	@Override
	public void configure(Binder binder) {
		List<MethodInterceptor> inteceptors = inteceptorManager.getMethodInterceptors();
		for(MethodInterceptor methodInterceptor : inteceptors){
			binder.bindInterceptor(Matchers.any(), Matchers.annotatedWith(PointCut.class), methodInterceptor);
		}
		bindBean(binder);
	}

	
	/**
	 * guice依赖注入
	 * @param binder
	 */
	@SuppressWarnings({ "rawtypes", "unchecked" })
	private void bindBean(Binder binder) {
		List<Class<?>> list = PackageUtil.scanPackage(jfastConfig.getPackageList());
		for(Class c : list){
			if(c.isAnnotationPresent(Bean.class)){
				Class<?>[] classes = c.getInterfaces();
				for(Class cla : classes){
					if (cla == Serializable.class) {
	                    continue;
	                }
					try {
						binder.bind(cla).to(c);
					} catch (Exception e) {
						
					}
				}
			}
		}
	}
}
